package com.yt.sys.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.sys.models.bo.LoginInfoSaveBO;
import com.yt.sys.models.bo.LoginRequest;
import com.yt.sys.models.bo.SysRolePermissionBO;
import com.yt.sys.models.dto.*;
import com.yt.sys.models.service.*;
import com.yt.sys.models.vo.AddAccountRequest;
import com.yt.sys.models.vo.SysUserVO;
import com.yt.sys.models.vo.UserInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import com.yt.sys.models.bo.LoginInfoBO;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 登录信息控制器
 *
 * @author lizicong
 * @Date 2025-10-25 00:32:05
 */

@RestController
@RequestMapping("/api/loginInfo")
@Slf4j
@Api(value = "LoginInfoApiController",tags = "登录信息Api接口")
public class LoginInfoApiController {

    @DubboReference
    private ILoginInfoService loginInfoService;

    @DubboReference
    private ISysUserService sysuserService;
    @DubboReference
    private ISysRoleService sysRoleService;
    @DubboReference
    private ISysUserRoleService sysUserRoleService;
    @DubboReference
    private ISysRolePermissionService sysRolePermissionService;
    @DubboReference
    private ISysPermissionService sysPermissionService;

    //根据用户id获取用户信息
    @PostMapping("/getUserInfo")
    @ApiOperation(value = "根据用户id获取用户信息",notes = "根据用户id获取用户信息")
    @ApiImplicitParam(name = "userId",value = "用户id",required = true,paramType = "query", dataType = "Long")
    public Result<UserInfoVO> getUserInfo(@RequestParam(value = "userId" ,required = false) Long userId ) {
        if (userId == null) {
            return new Result<>(CodeEnum.FAIL_100002.getCode(),"用户id不能为空");
        }
        UserInfoVO userInfoVO = new UserInfoVO();

        SysUserDTO sysUserDTO  = sysuserService.selectById(userId);
        if (sysUserDTO == null){
            return new Result<>(CodeEnum.FAIL_100002.getCode(),"用户不存在");
        }
        userInfoVO.setUser(sysUserDTO);
        //获取用户角色列表
        Wrapper<SysUserRoleDTO> userRoleWrapper = new EntityWrapper<>();
        userRoleWrapper.eq("user_id",userId);
        List<SysUserRoleDTO> userRoleList = sysUserRoleService.selectList(userRoleWrapper);

        List<SysRoleDTO> roles = new ArrayList<>();
        if (userRoleList != null && !userRoleList.isEmpty()) {
            List<Long> roleIds = userRoleList.stream()
                    .map(SysUserRoleDTO::getRoleId)
                    .collect(Collectors.toList());

            Wrapper<SysRoleDTO> roleWrapper = new EntityWrapper<>();
            roleWrapper.in("id", roleIds);
            roleWrapper.eq("status", 1); // 只查询启用状态的角色
            roles = sysRoleService.selectList(roleWrapper);
        }
        userInfoVO.setRoles(roles);

        // 获取用户权限列表
        List<SysPermissionDTO> permissions = new ArrayList<>();
        if (userRoleList != null && !userRoleList.isEmpty()) {
            List<Long> roleIds = userRoleList.stream()
                    .map(SysUserRoleDTO::getRoleId)
                    .collect(Collectors.toList());

            // 查询角色权限关联信息
            Wrapper<SysRolePermissionDTO> rolePermissionWrapper = new EntityWrapper<>();
            rolePermissionWrapper.in("role_id", roleIds);
            List<SysRolePermissionDTO> rolePermissions = sysRolePermissionService.selectList(rolePermissionWrapper);

            if (rolePermissions != null && !rolePermissions.isEmpty()) {
                List<Long> permissionIds = rolePermissions.stream()
                        .map(SysRolePermissionDTO::getPermissionId)
                        .collect(Collectors.toList());

                // 查询权限信息
                Wrapper<SysPermissionDTO> permissionWrapper = new EntityWrapper<>();
                permissionWrapper.in("id", permissionIds);
                permissionWrapper.eq("status", 1); // 只查询启用状态的权限
                permissions = sysPermissionService.selectList(permissionWrapper);
            }
        }
        userInfoVO.setPermissions(permissions);

        return new Result<>(CodeEnum.SUCCESS.getCode(), "获取用户信息成功", userInfoVO);
    }

    @PostMapping("/get")
    @ApiOperation(value = "根据id查找",notes = "根据id查找")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
    public Result<LoginInfoDTO> get(@RequestParam("id") Long id){
        if(id == null){
            return new Result<>(CodeEnum.FAIL_100002 );
        }

        LoginInfoDTO dto = loginInfoService.selectById(id);

        return new Result<>(dto);
    }


    @ApiOperation(value = "登录信息列表",notes = "登录信息列表")
    @PostMapping("/queryPageList")
    public Result<Page<LoginInfoDTO>> queryPageList(LoginInfoBO bo){
        Wrapper<LoginInfoDTO> wrapper = new EntityWrapper<>();
                if (bo.getStatus() != null){
                    wrapper.eq("status", bo.getStatus());
                }
        if (bo.getStartDate() != null){
            wrapper.ge("create_time", bo.getStartDate());
        }
        if (bo.getEndDate() != null){
            wrapper.le("create_time", bo.getEndDate());

        }
        Page<LoginInfoDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        page = loginInfoService.selectPage(page, wrapper);

        return new Result<>(page);
    }

    @ApiOperation(value = "登录",notes = "登录")
    @PostMapping("/syslogin")
    public Result<LoginInfoDTO> syslogin(@RequestBody LoginRequest loginRequest){
        System.out.println(loginRequest.getAccount());
        System.out.println(loginRequest.getPassword());
        if(loginRequest.getAccount()==null||loginRequest.getAccount().trim().isEmpty()){
            return new Result<>(CodeEnum.FAIL_100002.getCode(),"账号不能为空");
        }
        if(loginRequest.getPassword()==null||loginRequest.getPassword().trim().isEmpty()){
            return new Result<>(CodeEnum.FAIL_100002.getCode(),"密码不能为空");
        }

        Wrapper<LoginInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("account",loginRequest.getAccount());
        wrapper.eq("status",1);
        List<LoginInfoDTO> list = loginInfoService.selectList(wrapper);
        if(list==null||list.isEmpty()){
            return new Result<>(CodeEnum.FAIL_100002.getCode(),"账号不存在或禁用");
        }
        LoginInfoDTO loginInfo = list.get(0);
        //密码校验使用加盐Md5加密
        String encryptedPassword = DigestUtils.md5DigestAsHex((loginRequest.getPassword() + loginInfo.getSalt()).getBytes());
        if (!encryptedPassword.equals(loginInfo.getPassword())) {
            return new Result<>(CodeEnum.FAIL_100004.getCode(), "密码错误");
        }
        loginInfo.setPassword(null);
        loginInfo.setSalt(null);

        return new Result<>(CodeEnum.SUCCESS.getCode(),"登录成功",loginInfo);
    }

    @ApiOperation(value = "为管理员添加登录账号",notes = "为管理员添加登录账号")
    @PostMapping("/addloginInfo")
    public Result<LoginInfoDTO> addloginInfo(@RequestBody AddAccountRequest request){
        if (request == null){
            return new Result<>(CodeEnum.FAIL_100002.getCode(),"参数不能为空");
        }
        if(request.getAccount()==null||request.getAccount().trim().isEmpty()){
            return new Result<>(CodeEnum.FAIL_100002.getCode(),"账号不能为空");
        }
        if(request.getPassword()==null||request.getPassword().trim().isEmpty()){
            return new Result<>(CodeEnum.FAIL_100002.getCode(),"密码不能为空");
        }
        if(request.getSysUserId()==null){
            return new Result<>(CodeEnum.FAIL_100002.getCode(),"请选择工作人员");
        }
        //创建登录信息对象
        LoginInfoSaveBO saveBO = new LoginInfoSaveBO();
        System.out.println(request.getSysUserId());
        saveBO.setSysUserId(request.getSysUserId());
        System.out.println(saveBO.getSysUserId());
        saveBO.setAccount(request.getAccount());

        //检验账号是否存在
        Wrapper<LoginInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("account",request.getAccount());
        List<LoginInfoDTO> list = loginInfoService.selectList(wrapper);
        if(list!=null&&!list.isEmpty()){
            return new Result<>(CodeEnum.FAIL_100003.getCode(),"账号已存在");
            }
        //对密码进行MD5加密
        String salt = UUID.randomUUID().toString().replace("-", "").substring(0, 6);
        String encryptedPassword = DigestUtils.md5DigestAsHex((request.getPassword() + salt).getBytes());
        saveBO.setPassword(encryptedPassword);
        saveBO.setSalt(salt);
        saveBO.setStatus(1);

        boolean result = loginInfoService.add(saveBO);
        if (result) {
            return new Result<>(CodeEnum.SUCCESS.getCode(), "账号创建成功");
        } else {
            return new Result<>(CodeEnum.FAIL_100007.getCode(), "账号创建失败");
        }
    }
}
